<template>
    <div class="login-container">
        <!-- 左侧登录区域 -->
        <div class="login-left">
            <div class="login-form-container">
                <div class="login-header">
                    <h2>欢迎回来</h2>
                </div>
                
                <a-form
                    ref="loginFormRef"
                    :model="loginForm"
                    :rules="loginRules"
                    layout="vertical"
                    class="login-form"
                >
                    <a-form-item label="账号" name="username">
                        <a-input
                            v-model="loginForm.username"
                            placeholder="请输入用户名"
                            size="large"
                        />
                    </a-form-item>
                    
                    <a-form-item label="密码" name="password">
                        <a-input-password
                            v-model="loginForm.password"
                            placeholder="请输入密码"
                            size="large"
                            :visibility-toggle="true"
                            @keyup.enter="handleLogin"
                        />
                    </a-form-item>
                    
                    <a-form-item>
                        <div class="form-options">
                            <a-checkbox v-model="rememberMe">
                                记住密码
                            </a-checkbox>
                            <a class="forgot-password" @click="handleForgotPassword">
                                忘记密码？
                            </a>
                        </div>
                    </a-form-item>
                    
                    <a-form-item>
                        <a-button
                            type="primary"
                            size="large"
                            block
                            :loading="loading"
                            class="login-btn"
                            @click="handleLogin"
                        >
                            {{ loading ? '登录中...' : '登录' }}
                        </a-button>
                    </a-form-item>
                </a-form>
                <div class="copyright-text">
                    © 2025 Report Dida. All rights reserved
                </div>
            </div>
        </div>
        
        <!-- 右侧注册引导区域 -->
        <div class="login-right">
            <div class="register-guide">
                <div class="register-content">
                    <h3>还未注册？</h3>
                    <p>立即注册，发现大量机会！</p>
                    <a-button 
                        type="default" 
                        size="large" 
                        class="register-btn"
                        @click="openRegisterWebsite"
                    >
                        注册
                    </a-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import cefSharpUtils from '@/util/cefsharp'
import { openExternalBrowserLink } from '@/api/TabAxios/base'

export default {
    data() {
        return {
            loading: false,
            rememberMe: true,
            // 环境检测状态
            envDetection: {
                isCefSharp: false,
                checking: true,
                attempts: 0,
                maxAttempts: 6, // 5次重试 + 1次初始检测
                detectedAt: null
            },
            loginForm: {
                username: '',
                password: ''
            },
            loginRules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 3, message: '密码长度不能少于 3 个字符', trigger: 'blur' }
                ]
            }
        }
    },
    computed: {
        isCefSharpEnv() {
            return this.envDetection.isCefSharp
        }
    },
    async mounted() {
        // 页面加载时检查是否已登录
        if (this.$store.getters['token/isLogin']) {
            this.redirectToHome()
            return
        }
        
        // 恢复记住我功能
        const rememberedUsername = localStorage.getItem('rememberedUsername')
        const rememberMe = localStorage.getItem('rememberMe') === 'true'
        
        if (rememberMe && rememberedUsername) {
            this.loginForm.username = rememberedUsername
            this.rememberMe = true
            console.log('🔍 [Login] 恢复记住的用户名:', rememberedUsername)
        }
        
        // 异步检测CEFSharp环境
        await this.detectEnvironment()
    },
    methods: {
        // 异步环境检测
        async detectEnvironment() {
            console.log('🔍 [Login] 开始环境检测...')
            this.envDetection.checking = true
            this.envDetection.attempts = 0
            
            try {
                const result = await cefSharpUtils.checkEnvironmentAsync({
                    maxRetries: 5,
                    retryDelay: 500,
                    initialDelay: 100
                })
                
                this.envDetection.isCefSharp = result.isCefSharp
                this.envDetection.attempts = result.attempts
                this.envDetection.detectedAt = result.detectedAt
                this.envDetection.checking = false
                
                console.log('🔍 [Login] 环境检测完成:', {
                    isCefSharp: result.isCefSharp,
                    attempts: result.attempts,
                    hasStore: !!this.$store
                })
                
                // 如果是CEFSharp环境，可以在这里添加额外的初始化逻辑
                if (result.isCefSharp) {
                    console.log('✅ [Login] CEFSharp环境已就绪')
                } else {
                    console.log('ℹ️ [Login] 使用标准Web模式')
                }
                
            } catch (error) {
                console.error('❌ [Login] 环境检测异常:', error)
                this.envDetection.checking = false
                this.envDetection.isCefSharp = false
            }
        },
        
        // 获取当前环境状态（用于登录逻辑）
        getCurrentEnvironment() {
            // 如果还在检测中，使用同步检测作为后备
            if (this.envDetection.checking) {
                const syncResult = cefSharpUtils.checkEnvironment()
                console.log('⚠️ [Login] 使用同步检测作为后备:', syncResult)
                return syncResult
            }
            return this.envDetection.isCefSharp
        },
        
        handleLogin() {
            // 手动验证表单
            const username = this.loginForm.username.trim()
            const password = this.loginForm.password.trim()
            
            // 检查用户名
            if (!username) {
                this.$message.error('请输入用户名')
                return
            }
            
            if (username.length < 3 || username.length > 20) {
                this.$message.error('用户名长度在 3 到 20 个字符')
                return
            }
            
            // 检查密码
            if (!password) {
                this.$message.error('请输入密码')
                return
            }
            
            if (password.length < 3) {
                this.$message.error('密码长度不能少于 3 个字符')
                return
            }
            
            // 获取当前环境状态
            const isCefSharp = this.getCurrentEnvironment()
            console.log('🔍 [Login] 环境检测:', { isCefSharp })
            
            this.loading = true
            
            // 准备登录数据
            const loginData = {
                username,
                password
            }
            
            // 如果不是CEFSharp环境，进行默认账号密码验证
            if (!isCefSharp) {
                const defaultUsername = 'admin'
                const defaultPassword = '123456'
                
                if (username !== defaultUsername || password !== defaultPassword) {
                    this.loading = false
                    this.$message.error('用户名或密码错误！默认账号：admin，密码：123456')
                    return
                }
            }
            
            // 调用store登录方法
            this.$store.dispatch('token/login', loginData)
                .then(response => {
                    this.loading = false
                    console.log('✅ [Login] 登录成功:', response)
                    
                    // 根据环境显示不同的成功消息
                    if (isCefSharp) {
                        this.$message.success('CEFSharp登录成功！')
                    } else {
                        this.$message.success('登录成功！')
                    }
                    
                    // 记住我功能
                    if (this.rememberMe) {
                        localStorage.setItem('rememberedUsername', username)
                        localStorage.setItem('rememberMe', 'true')
                    } else {
                        localStorage.removeItem('rememberedUsername')
                        localStorage.removeItem('rememberMe')
                    }
                    
                    this.redirectToHome()
                })
                .catch(error => {
                    this.loading = false
                    console.error('❌ [Login] 登录失败:', error)
                    
                    // 根据错误类型显示不同的错误消息
                    let errorMessage = '登录失败，请重试'
                    if (error && error.message) {
                        if (error.message.includes('用户名或密码错误')) {
                            errorMessage = '用户名或密码错误'
                        } else if (error.message.includes('cefSharp环境不可用')) {
                            errorMessage = 'CEFSharp环境不可用，请检查环境配置'
                        } else if (error.message.includes('SSL connection')) {
                            errorMessage = 'SSL连接失败，请检查网络配置'
                        } else {
                            errorMessage = error.message
                        }
                    }
                    
                    this.$message.error(errorMessage)
                })
        },
        redirectToHome() {
            if (this.$route.query.redirect) {
                this.$router.replace({
                    path: this.$route.query.redirect
                })
            } else {
                this.$router.replace({ path: '/home' })
            }
        },
        // 打开注册网站
        async openRegisterWebsite() {
            // 打开注册页面
            const param = {
                url: 'https://www.didalink.com/api/app/user/login',
                type: 'register'
            }
            const res = await openExternalBrowserLink(JSON.stringify(param))
            console.log('🔍 [Register] 打开注册页面:', res)
            if (res.code === 0) {
                console.log('✅ [Register] 成功打开注册页面')
                this.$message.success('正在为您打开注册页面...')
            } else {
                console.error('❌ [Register] 打开注册页面失败:', res)
                this.$message.error('打开注册页面失败，请手动访问注册网站')
            }
        },
        async handleForgotPassword() {
            // 打开忘记密码页面
            const param = {
                url: 'https://www.didalink.com/api/app/user/login',
                type: 'register'
            }
            const res = await openExternalBrowserLink(JSON.stringify(param))
            console.log('🔍 [Register] 打开忘记密码页面:', res)
            if (res.code === 0) {
                console.log('✅ [Register] 成功打开忘记密码页面')
                this.$message.success('正在为您打开忘记密码页面...')
            } else {
                console.error('❌ [Register] 打开忘记密码页面失败:', res)
                this.$message.error('打开忘记密码页面失败，请手动访问注册网站')
            }
        }
    }
}
</script>

<style scoped>
.login-container {
    min-height: 100vh;
    display: flex;
    align-items: stretch;
    justify-content: center;
    background: url('https://res.cloudinary.com/dci1eujqw/image/upload/v1616769558/Codepen/waldemar-brandt-aThdSdgx0YM-unsplash_cnq4sb.jpg');
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    padding: 0;
    gap: 0;
}
.login-left {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    background: transparent;
    padding: 60px 0 60px 60px; /* 去除内侧间距，让中间仅由gap控制 */
    max-width: 50%;
}
.login-form-container {
    width: 100%;
    max-width: 400px;
    height: 520px;
    background: rgba(255, 255, 255, 0.98);
    padding: 40px;
    border-radius: 16px 0 0 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.25);
    border: 1px solid rgba(255, 255, 255, 0.4);
    border-right: none;
    backdrop-filter: blur(10px);
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: center;
}
.copyright-text {
    position: absolute;
    bottom: -40px;
    left: 0;
    right: 0;
    text-align: center;
    color: rgba(255, 255, 255, 0.8);
    font-size: 14px;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}
.login-right {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    background: transparent;
    background-image: none;
    background-size: 60px 60px;
    padding: 60px 60px 60px 0; /* 去除内侧间距，让中间仅由gap控制 */
    max-width: 50%;
    position: relative;
    overflow: hidden;
}
.login-right::before {
    content: '';
    position: absolute;
    top: -50%;
    right: -50%;
    width: 200%;
    height: 200%;
    background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 1px, transparent 1px);
    background-size: 50px 50px;
    animation: float 20s ease-in-out infinite;
}
@keyframes float {
    0%,
    100% { transform: translateY(0) rotate(0deg); }
    50% { transform: translateY(-20px) rotate(180deg); }
}
.login-header {
    text-align: left;
    margin-bottom: 40px;
}
.login-header h2 {
    color: #333;
    margin-bottom: 8px;
    font-size: 32px;
    font-weight: 700;
    line-height: 1.2;
}
.login-form {
    width: 100%;
}
::deep(.ant-form-item-label > label) {
    font-weight: 600;
    color: #333;
    font-size: 14px;
}
::deep(.ant-input),
::deep(.ant-input-password) {
    border-radius: 8px;
    border: 1px solid #e1e5e9;
    padding: 12px 16px;
    font-size: 14px;
    height: 48px;
    transition: all 0.3s ease;
}
::deep(.ant-input:focus),
::deep(.ant-input-password:focus) {
    border-color: #667eea;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
::deep(.ant-input-affix-wrapper) {
    border-radius: 8px;
    border: 1px solid #e1e5e9;
    padding: 0;
    height: 48px;
    display: flex;
    align-items: center;
}
::deep(.ant-input-affix-wrapper:focus-within) {
    border-color: #667eea;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
::deep(.ant-input-affix-wrapper .ant-input) {
    border: none;
    padding: 12px 16px;
    box-shadow: none;
    height: 100%;
}
::deep(.ant-input-affix-wrapper .ant-input:focus) {
    border: none;
    box-shadow: none;
}
.form-options {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: -8px 0 8px 0;
}
::deep(.ant-checkbox-wrapper) {
    color: #666;
    font-size: 14px;
}
::deep(.ant-checkbox-checked .ant-checkbox-inner) {
    background-color: #667eea;
    border-color: #667eea;
}
.forgot-password {
    color: #667eea;
    font-size: 14px;
    text-decoration: none;
    cursor: pointer;
    transition: color 0.3s ease;
}
.forgot-password:hover {
    color: #5a6fd8;
    text-decoration: underline;
}
.login-btn {
    background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
    border: none;
    border-radius: 8px;
    height: 48px;
    font-weight: 600;
    font-size: 16px;
    margin-bottom: 12px;
    transition: all 0.3s ease;
}
.login-btn:hover {
    background: linear-gradient(135deg, #2563eb 0%, #1e40af 100%);
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(37, 99, 235, 0.35);
}
.register-guide {
    text-align: center;
    color: white;
    position: relative;
    z-index: 2;
    height: 520px;
    background: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(15px);
    -webkit-backdrop-filter: blur(15px);
    border-radius: 0 16px 16px 0;
    border: 1px solid rgba(255, 255, 255, 0.2);
    border-left: none;
    padding: 40px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
.register-content h3 {
    color: white;
    margin-bottom: 16px;
    font-size: 28px;
    font-weight: 700;
    line-height: 1.2;
}
.register-content p {
    color: rgba(255, 255, 255, 0.9);
    font-size: 16px;
    margin-bottom: 32px;
    line-height: 1.5;
}
.register-btn {
    background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
    border: none;
    color: #fff;
    border-radius: 8px;
    height: 48px;
    font-weight: 600;
    font-size: 16px;
    min-width: 120px;
    backdrop-filter: blur(10px);
    transition: all 0.3s ease;
}
.register-btn:hover {
    background: linear-gradient(135deg, #2563eb 0%, #1e40af 100%);
    color: #fff;
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(37, 99, 235, 0.35);
}

/* 响应式设计 */
@media (max-width: 992px) {
    .login-container {
        flex-direction: column;
        min-height: auto;
        gap: 24px;
    }
    .login-left,
    .login-right {
        max-width: 100%;
        padding: 40px;
    }
    .login-left {
        min-height: 60vh;
    }
    .login-right {
        min-height: 40vh;
    }
    .login-form-container,
    .register-guide {
        height: 450px;
    }
    .login-form-container {
        border-radius: 16px;
        border: 1px solid rgba(255, 255, 255, 0.4);
    }
    .register-guide {
        border-radius: 16px;
        border: 1px solid rgba(255, 255, 255, 0.2);
    }
    .login-header h2 {
        font-size: 28px;
    }
    .register-content h3 {
        font-size: 24px;
    }
}
@media (max-width: 768px) {
    .login-left,
    .login-right {
        padding: 30px 20px;
    }
    .login-form-container,
    .register-guide {
        height: 400px;
    }
    .login-header {
        margin-bottom: 30px;
    }
    .login-header h2 {
        font-size: 24px;
    }
    .register-content h3 {
        font-size: 20px;
    }
    .register-content p {
        font-size: 14px;
    }
}
@media (max-width: 480px) {
    .login-container {
        padding: 0;
    }
    .login-left,
    .login-right {
        padding: 20px;
        margin: 0;
    }
    .login-form-container,
    .register-guide {
        height: 350px;
    }
    .login-header h2 {
        font-size: 22px;
        text-align: center;
    }
    .login-header {
        text-align: center;
    }
}
</style>
